using System.Collections.Generic;
using UnityEngine;
using YooAsset.Editor;
using YooAsset;
using UnityEditor;

namespace shacoEditor
{
    public class YooAssetsBuildHelper
    {
        static public void BuildYooAssetPackage(string packageName)
        {
            var PackageName = packageName;
            var BuildPipeline = EBuildPipeline.ScriptableBuildPipeline;
            var BuildTarget = UnityEditor.EditorUserBuildSettings.activeBuildTarget;

            //以下代码参考自 YooAsset.Editor.ScriptableBuildPipelineViewer.ExecuteBuild()
            var fileNameStyle = AssetBundleBuilderSetting.GetPackageFileNameStyle(PackageName, BuildPipeline);
            var buildinFileCopyOption = AssetBundleBuilderSetting.GetPackageBuildinFileCopyOption(PackageName, BuildPipeline);
            var buildinFileCopyParams = AssetBundleBuilderSetting.GetPackageBuildinFileCopyParams(PackageName, BuildPipeline);
            var compressOption = AssetBundleBuilderSetting.GetPackageCompressOption(PackageName, BuildPipeline);

            ScriptableBuildParameters buildParameters = new ScriptableBuildParameters();
            buildParameters.BuildOutputRoot = AssetBundleBuilderHelper.GetDefaultBuildOutputRoot();
            buildParameters.BuildinFileRoot = AssetBundleBuilderHelper.GetStreamingAssetsRoot();
            buildParameters.BuildPipeline = BuildPipeline.ToString();
            buildParameters.BuildTarget = BuildTarget;
            buildParameters.PackageName = PackageName;
            buildParameters.PackageVersion = GetDefaultPackageVersion();
            buildParameters.EnableSharePackRule = true;
            buildParameters.BuildBundleType = 2;//(int)EBuildBundleType.AssetBundle;
            buildParameters.VerifyBuildingResult = true;
            buildParameters.FileNameStyle = fileNameStyle;
            buildParameters.BuildinFileCopyOption = buildinFileCopyOption;
            buildParameters.BuildinFileCopyParams = buildinFileCopyParams;
            buildParameters.EncryptionServices = CreateEncryptionInstance(packageName);
            buildParameters.CompressOption = compressOption;

            ScriptableBuildPipeline pipeline = new ScriptableBuildPipeline();
            var buildResult = pipeline.Run(buildParameters, true);
            if (buildResult.Success)
            {
                ReplaceYooAssetPackage(PackageName, buildResult.OutputPackageDirectory, BuildTarget);
            }
        }

        static public void BuildYooAssetSimulatorManifest(string packageName)
        {
            var buildParam = new EditorSimulateBuildParam();
            buildParam.BuildPipelineName = EBuildPipeline.EditorSimulateBuildPipeline.ToString();
            buildParam.PackageName = packageName;
            var result = AssetBundleSimulateBuilder.SimulateBuild(buildParam);

            var copyFilePath = System.IO.Directory.GetFiles(result.PackageRootDirectory);
            var streamingAssetRoot = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{packageName}";

            if (!System.IO.Directory.Exists(streamingAssetRoot))
                System.IO.Directory.CreateDirectory(streamingAssetRoot);

            var oldFiles = System.IO.Directory.GetFiles(streamingAssetRoot);
            foreach (var iter in oldFiles)
                System.IO.File.Delete(iter);

            if (!System.IO.Directory.Exists(streamingAssetRoot))
                System.IO.Directory.CreateDirectory(streamingAssetRoot);

            foreach (var iter in copyFilePath)
            {
                var fileName = System.IO.Path.GetFileName(iter);
                var pastPath = $"{streamingAssetRoot}/{fileName}";
                System.IO.File.Copy(iter, pastPath, true);
            }
            Debug.Log($"拷贝模拟资源列表{packageName}到StreamingAsset目录完毕");
        }

        static string GetDefaultPackageVersion()
        {
            int totalMinutes = System.DateTime.Now.Hour * 60 + System.DateTime.Now.Minute;
            return System.DateTime.Now.ToString("yyyy-MM-dd") + "-" + totalMinutes;
        }

        static YooAsset.IEncryptionServices CreateEncryptionInstance(string packageName)
        {
            var BuildPipeline = EBuildPipeline.ScriptableBuildPipeline;

            var encyptionClassName = AssetBundleBuilderSetting.GetPackageEncyptionClassName(packageName, BuildPipeline);
            var encryptionClassTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
            var classType = encryptionClassTypes.Find(x => x.FullName.Equals(encyptionClassName));
            if (classType != null)
                return (IEncryptionServices)System.Activator.CreateInstance(classType);
            else
                return null;
        }

        static void ReplaceYooAssetPackage(string PackageName, string outputDir, BuildTarget BuildTarget)
        {
            var outDir = Application.dataPath.Remove(Application.dataPath.IndexOf("/Assets"), "/Assets".Length) + $"/Bundles/{BuildTarget}/Output";
            if (!System.IO.Directory.Exists(outDir))
                System.IO.Directory.CreateDirectory(outDir);

            var pastTo = $"{outDir}/{PackageName}";
            var dirName = System.IO.Path.GetDirectoryName(pastTo);
            if (System.IO.Directory.Exists(pastTo))
            {
                EditorUtility.DisplayProgressBar("删除旧资源目录中...", dirName, 0.8f);
                System.IO.Directory.Delete(pastTo, true);
            }

            EditorUtility.DisplayProgressBar("移动资源目录中...", dirName, 0.9f);
            System.IO.Directory.Move(outputDir, pastTo);
            EditorUtility.RevealInFinder(pastTo);
            EditorUtility.ClearProgressBar();
        }
    }
}
